angular.module("app.login")

    .factory("loginService", ["$http", "$q", "config", function ($http, $q, config) {
        var baseUrl = config.baseUrl;

        var _token = null;
        var _user = null;
        var _rememberMe = false;

        var ret = {};

        var _getAccessToken = function () {
            return _token || localStorage.token || sessionStorage.token;
        };

        ret.login = function (loginInfo, rememberMe) {
            _rememberMe = rememberMe;
            if (rememberMe) {
                localStorage.rememberMe = rememberMe;
            } else {
                localStorage.removeItem("rememberMe");
            }

            var url = baseUrl + "/login";

            var deferred = $q.defer();
            //TODO部门？？
            $http.post(url, loginInfo).then(function (res) {
                var respObj = res.data;

                if (!respObj) {
                    return deferred.reject("服务器没有响应");
                }

                if (!respObj.success) {
                    return deferred.reject(respObj.errMsg || "用户名或密码错误");
                }

                _token = respObj.data;
                if (rememberMe) {
                    localStorage.token = _token;
                } else {
                    sessionStorage.token = _token;
                }
                deferred.resolve(_token);
            }, function (res) {
                deferred.reject(res.errMsg || "登录失败");
            });
            return deferred.promise;
        };

        ret.isLoggedIn = function () {
            var token = _getAccessToken();
            return !!token;
        };

        ret.getAccessToken = _getAccessToken;

        ret.logout = function () {
            localStorage.removeItem("token");
            sessionStorage.removeItem("token");
        };

        var querying = false;
        var _getUser = function (forceRefresh) {
            var deferred = $q.defer();
            if (!forceRefresh && _user) {
                deferred.resolve(_user);
                return deferred.promise;
            }

            if(querying) {
                setTimeout(function() {
                    _getUser().then(function(user) {
                        deferred.resolve(user);
                    }, function(err) {
                        deferred.reject(err);
                    });
                }, 200);
                return deferred.promise;
            }

            querying = true;
            var url = baseUrl + "/profile";
            $http.get(url).then(function (res) {
                _user = res.data.data;
                deferred.resolve(_user);
                querying = false;
            }, function (res) {
                deferred.reject(res.errMsg || "获取用户信息失败");
                querying = false;
            });
            return deferred.promise;
        };
        ret.getUser = _getUser;

        return ret;
    }]);